<?php 

namespace Modules\Core\Traits;

trait Statable
{
    public function target_stat()
    {
        $resourceType = str_singular($this->table);
        return $this->hasOne('\Modules\Core\Entities\Stat', 'target_id')->where('target_type', $resourceType);
    }

    public function createStat()
    {
        $this->target_stat()->create([
            'uuid' => uniqid(),
            'target_type' => str_singular($this->table),
            'data' => []
        ]);
    }

    public function findOrCreateStat()
    {
        if (is_null($this->target_stat)) {
            $this->createStat();
            $this->target_stat = $this->target_stat()->first();
        }
    }

    public function updateStat($key, $change)
    {
        $this->findOrCreateStat();

        $data = $this->target_stat->data;
        $data[$key] = @v($data[$key], 0) + $change;

        $this->target_stat->data = $data;
        $this->target_stat->save();
    }

    public function stats($field)
    {
        $this->findOrCreateStat();

        $data = $this->target_stat->data;

        $result = [];

        foreach ($field as $key => $value) {
            if (is_string($key))
                $result[$key] = @v($data[$key], $value);
            else 
                $result[$value] = @v($data[$value], 0);
        }

        return $result;
    }
}
?>